<?php
	session_start();
	$UserID = trim($_SESSION['user_id']);
	if($UserID == "" || $UserID == 0) {
		header("Location: index.php?page=login");
	}
	if(isset($_GET['del'])) {
		$del = intval($_GET['del']);
		$del_sql = "DELETE FROM tbl_references WHERE User='".$UserID."' AND ID='".$del."'";
		$del_sql2 = "DELETE FROM composedocument WHERE username='".$UserID."' AND title_reference='".$del."'";
		$del_res = mysql_query($del_sql);
		if($del_res) {
			$del_res2 = mysql_query($del_sql2);	
			header("Location: index.php?page=my_saved_bibliographies");
		}
	} else {
		$tr = isset($_GET['tr']) ? intval($_GET['tr']) : 0;
		if($tr == 0) {
			$n_sql = "SELECT * FROM tbl_references WHERE User='".$UserID."' ORDER BY UpdatedDate DESC LIMIT 1";
		} else $n_sql = "SELECT * FROM tbl_references WHERE ID='".$tr."' AND User='".$UserID."'";
		$result = mysql_query($n_sql);
		$detail = mysql_fetch_row($result);
		$_SESSION['tr_dload'] = $detail[0];
	}
?>
<style type="text/css">
.func_icon {
	height: 30px;
	background-color: #333333;
	color: #ffffff;
	padding: 5px 0 5px 15px;
}
a.func_icon:link {text-decoration: none; color: #ffffff;}
a.func_icon:visited {text-decoration: none; color: #ffffff;}
a.func_icon:hover {text-decoration: none; color:#FF3; }

.title_rf{
	margin-top: 3px;
	text-align: center;
	font-family: Verdana, Geneva, sans-serif;
	font-size: 18px;
	font-weight: bold;
	background-color: #CACACA;
}
.ti_re2 {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 10px;
	color: #616161;
	padding: 1px 0 3px 3px;
}
.ti_re {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 11px;
	color: #00F;
	padding: 1px 0 3px 3px;
}
.ti_re a:link {text-decoration:none; color: #00F;}
.ti_re a:visited {text-decoration:none; color: #00F;}
.ti_re a:hover { text-decoration: none; color: #ff0000;}
</style>
<script language="javascript" type="text/javascript">
<?php
	$true_host = $_SERVER['HTTP_HOST'];
	echo 'var true_uri ="http://'.$true_host.'";';
	
	function getFormatEdition($edition)
	{	
		$result = str_replace('st', '<sup>st</sup>', $edition);
		$result = str_replace('nd', '<sup>nd</sup>', $result);
		$result = str_replace('rd', '<sup>rd</sup>', $result);
		$result = str_replace('th', '<sup>th</sup>', $result);			
		return $result;
	}
	
	function getLastName($name)
	{
		$lastName = "";
		$temp = str_replace('`', ' ', $name);
		$splitName = explode(' ', $temp);						
		$countSplitName = count($splitName);
		if ($countSplitName > 0)
		{
			$lastName = $splitName[$countSplitName - 1];
			$length = strlen($lastName);
			if ($length > 0)
			{
				$lastName = strtoupper($lastName[0]) . strtolower(substr($lastName, 1));
			}
		}		
		
		return $lastName;			
	}
	
	function getInitialFirstName($name)
	{
		$initial = "";
		$temp = str_replace('`', ' ', $name);
		$splitName = explode(' ', $temp);			
		$countSplitName = count($splitName);
		if ($countSplitName > 0)
		{
			$initial = strtoupper($splitName[0]);
			$initial = $initial[0];
		}
		return $initial;
	}
	
  function doubleQuoteJS($text)
  {
	$result = str_replace('"', '\\"', $text);
	return $result;
  }
  
	@session_start();
	$UserID = trim($_SESSION['user_id']);
	if($UserID == "")
	{
		$UserID = session_id();		
	}
?>
function show_alert() {
	if(confirm('Are you sure you wish to delete these references. You cannot undo this action.')) {
		window.location = "./index.php?page=my_saved_bibliographies&del=<?php echo $detail['0'] ?>"
	}
}
function show_txt_title() {
	$('#txt_title').hide();
	$('#txt_title2').show();	
}
function edit_txt_title() {
	//var xurl = true_uri + '/aw/application/edit_title.php';
	var xurl = true_uri + '/application/edit_title.php';
	$.ajax({
		type: 'POST',
		url: xurl,
		data: ({txt_title: $('#text_title').val(), user: '<?php echo $UserID; ?>', title_id: '<?php echo $detail[0]; ?>'}),
		dataType: 'html',
		cache: false,
		success: function(data) {
			$('#txt_title').html($('#text_title').val());
			$('#txt_title2').hide();
			$('#txt_title').show();
		},
		error: function(xhr) {
			alert('Error! Status = ' + xhr.status);
		}
	});	
}	

function sendEmailToMe(tr)
{
	var url = "";
	if (tr)	
		url = "email_file_references.php?tr=" + tr;
	else
		url = "email_file_references.php";
	$("#loadingDataAjax").fadeIn();
	$.get(url, function(args){
		if (args == "false")
		{
			alert("Please login before send email");
		}
		else
		{
			alert("Your request was sent to your email");
		}
		$("#loadingDataAjax").fadeOut();
	});
}
</script>
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse">	
	<tr>
    	<!-- My saved bibliography -->
        <td width="270px" valign="top">
			<div style="text-align:center;background-color:#9CF; padding: 4px;font-weight:bold">
				<span/>Saved References</span>
			</div>
			<div style="height: 300px;background-color: white;overflow: auto;border:1px solid #9CF">
				<table width="100%" style="border-collapse:collapse;">
					<tr>
						<td>
							<table width="100%">
								<?php 
									$sql = "SELECT * FROM tbl_references WHERE User='".$UserID."' ORDER BY UpdatedDate DESC";
									$res = mysql_query($sql);
									//$list = mysql_fetch_array($res);
									//print_r($list);//exit;
									while($list = mysql_fetch_array($res)) {
								?>
								<tr>
									<td style="padding: 1px 0 3px 3px;"><div class="ti_re"><a href="./index.php?page=my_saved_bibliographies&tr=<?php echo $list['ID']; ?>"><?php echo $list['Title_Reference']." @ ". date_format(new DateTime($list['UpdatedDate']),"m/d/y h:iA"); ?></a></div>
									<?php 
										$sql2 = "SELECT COUNT(*) FROM composedocument WHERE username='".$UserID."' AND title_reference='".$list['ID']."' AND types!='compose'";
										$res2 = mysql_query($sql2);
										$num = mysql_fetch_row($res2);
										if($num[0] > 1) {
											$num_str = $num[0]." citations";
										} else $num_str = $num[0]." citation";
									?>
									<div class="ti_re2"><?php echo $num_str; ?></div>
									</td>
								</tr>
								<?php } ?>
							</table>
						</td>
					</tr>
				</table>
			</div>
			<div style="text-align:center;background-color:#9CF; padding: 4px;font-weight:bold">
				<span><a href="javascript:void(0)" onclick="sendEmailToMe()"><img align="absmiddle" height="20px" src="./images/email.png" border="0" />&nbsp;Send all references to my email</a></span>
			</div>
		</td>
        <!-- // end -->
        <td width="10px">&nbsp;</td>
        <!-- show content and all functions -->
        <td valign="top">			
        	<table width="100%">
            	<tr>
                	<td class="func_icon">
						<?php if ($detail['0']){ ?>
                    	<div>
                        	<span><a class="func_icon" href="./index.php?page=assignment_manager&tr=<?php echo $detail['0'] ?>"><img align="absmiddle" src="./images/open-edit-bib.png" border="0" />&nbsp;Open & Edit</a></span>&nbsp;&nbsp;&nbsp;&nbsp;
							<span><a class="func_icon" href="#" onclick="show_txt_title();"><img align="absmiddle" src="./images/rename-saved-bib.png" border="0" />&nbsp;Rename</a></span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span><a class="func_icon" href="./download.php"><img align="absmiddle" src="./images/download-saved-bib.png" border="0" />&nbsp;Download</a></span>&nbsp;&nbsp;&nbsp;&nbsp;
							<span><a class="func_icon" href="javascript:void(0)" onclick="sendEmailToMe('<?php echo $detail['0'] ?>')"><img align="absmiddle" height="20px" src="./images/email.png" border="0" />&nbsp;Send to me</a></span>&nbsp;&nbsp;&nbsp;&nbsp;                            
                            <span><a class="func_icon" onclick="show_alert();" href="javascript:void(0);"><img align="absmiddle" src="./images/delete-saved-bib.png" border="0" />&nbsp;Delete</a></span>&nbsp;&nbsp;&nbsp;&nbsp;
                        </div>
						<?php } ?>
                    </td>
                </tr>
                <tr>
                	<td class="title_rf">
                    	<div id="txt_title" style="display:''"><b><?php echo $detail['1']; ?></b><a href="#" onclick="show_txt_title();"></div>
            <div id="txt_title2" style="display:none"><input type="text" id="text_title" name="text_title" value="<?php echo $detail['1']; ?>" />&nbsp;&nbsp;<input type="button" name="btn_title" value="OK" onclick="edit_txt_title();" /></div>
                    </td>
                </tr>
                <tr>
                	<td height="2px">&nbsp;</td>
                </tr>
                <tr>
                	<td style="border: 0px solid #C4C4C4; padding: 3px 3px 3px 15px;">
                    	<?php
							$citationListForJS = "\"[{";
							$citationListToInsertForJS = "\"";
							
							$m_sql = "SELECT * FROM composedocument WHERE username='".$UserID."' AND title_reference='".$detail['0']."' and types!='compose' ORDER BY id DESC";
							$m_res = mysql_query($m_sql);
							while($work = mysql_fetch_array($m_res)) {
						?>
                        <div>
                        <?php
                        $citationList = "";
		$all_name = "";
			$all_name = $work['firstname'] . "`" . $work['lastname'];
			if ($work['author'] != "")
				$all_name .= "," . $work['author'];
			$exp = explode(",",$all_name);			
			$count = count($exp);
			$result = "";			
			$year = doubleQuoteJS($work['pyear']);
			if ($work['types'] == 'book')
			{				
				$lastNameJS = "";	
				$citationOptions = "";
				
				if ($count == 1)
				{				
					$lastName = getLastName($exp[0]);
					$result = $lastName . ", " . getInitialFirstName($exp[0]) . ".";
					$lastNameJS = doubleQuoteJS($lastName);										
					
					$citationOptions = $lastNameJS . '(' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
					$citationOptions = "(" . $lastNameJS . ',' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ',';
				}
				else
				{
					$tempCitation = "";
					for($i = 0; $i < $count; $i++)
					{
						$lastName = getLastName($exp[$i]);					
						$tempLastNameJS = doubleQuoteJS($lastName);
						if( $i == $count - 1)
						{
							if ($count < 7)
							{
								$result .= "&" . $lastName . ", " . getInitialFirstName($exp[$i]);
							}
							else
							{
								$result .= "..." . $lastName . ", " . getInitialFirstName($exp[$i]);
							}
							
							if ($count < 3)
							{							
								$tempCitation =  substr($tempCitation, 0, strlen($tempCitation) - 2);
								
								$citationOptions = $tempCitation . ' and ' . $tempLastNameJS . '(' . $year . ')';
								$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
								$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
								
								$citationOptions = "(" . $tempCitation . ' & ' . $tempLastNameJS . ',' . $year . ')';	
								$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
								$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
							}
						}
						else
						{
							$result .= $lastName . ", " . getInitialFirstName($exp[$i]) . "., ";
							if ($count < 3)
							{
								$tempCitation .= $tempLastNameJS . ", ";
							}
						}						
					}
				}			
				
				if ($count >= 3)
				{				
					$lastName = getLastName($exp[0]);						
					$citationOptions = $lastName . ' et al (' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
					
					$citationOptions = '(' . $lastName . ' et al, ' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
				}
				if ($work['edition'] != "")
				{
					$result .= "(" . $year . "). <i>" . $work['booktitle'] . "</i>(" . 
						getFormatEdition($work['edition']) . "). " . $work['pcity'] . ": " . $work['publisher'] . ".";
				}
				else
				{
					$result .= "(" . $year . "). <i>" . $work['booktitle'] . "</i>. " . $work['pcity'] . ": " . $work['publisher'] . ".";
				}
			}
			else if ($work['types'] == 'journal')//journal
			{
				$lastNameJS = "";
				if ($count == 1)
				{	
					$lastName = getLastName($exp[0]);
					$result = $lastName . ", " . getInitialFirstName($exp[0]) . ".";
					$lastNameJS = doubleQuoteJS($lastName);										
					
					$citationOptions = $lastNameJS . '(' . $year . ',p.)';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
					$citationOptions = "(" . $lastNameJS . ',' . $year . ',p.)';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
				}
				else
				{
					$tempCitation = "";
					for($i = 0; $i < $count; $i++)
					{
						$lastName = getLastName($exp[$i]);					
						$tempLastNameJS = doubleQuoteJS($lastName);
						if( $i == $count - 1)
						{
							if ($count < 7)
							{
								$result .= "&" . $lastName . ", " . getInitialFirstName($exp[$i]);
							}
							else
							{
								$result .= "..." . $lastName . ", " . getInitialFirstName($exp[$i]);
							}
							
							if ($count < 3)
							{							
								$tempCitation =  substr($tempCitation, 0, strlen($tempCitation) - 2);
								
								$citationOptions = $tempCitation . ' and ' . $tempLastNameJS . '(' . $year . ')';
								$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
								$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
								
								$citationOptions = "(" . $tempCitation . ' & ' . $tempLastNameJS . ',' . $year . ')';	
								$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
								$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
							}
						}
						else
						{
							$result .= $lastName . ", " . getInitialFirstName($exp[$i]) . "., ";
							if ($count < 3)
							{
								$tempCitation .= $tempLastNameJS . ", ";
							}
						}						
					}
				}
				
				if ($count >= 3)
				{				
					$lastName = getLastName($exp[0]);						
					$citationOptions = $lastName . ' et al (' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
					
					$citationOptions = '(' . $lastName . ' et al, ' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
				}
				
				if ($count < 6)
				{	
					$result .= "(" . $year . "). " . $work['booktitle'] . ". <i>" . $work['journaltitle'] . "," . $work['issuenumber'] . "</i>(" . 
						$work['edition'] . "), " . $work['pagenumber'] . ".";
				}
				else
				{
					$result .= "(" . $year . "). " . $work['booktitle'] . ". <i>" . $work['journaltitle'] . "," . $work['issuenumber'] . "</i>, " . 
					$work['pagenumber'] . ".";
				}
				
				if ($work['digitalobject'] != "")
				{
					$result .= " doi:" . $work['digitalobject'];
				}
			}
			else if ($work['types'] == 'web')//website
			{
				$year = doubleQuoteJS($work['website_year']);
				$month = doubleQuoteJS($work['website_month']);
				$day = doubleQuoteJS($work['website_day']);
				
				$year_accessed = doubleQuoteJS($work['website_year_accessed']);
				$month_accessed = doubleQuoteJS($work['website_month_accessed']);
				$day_accessed = doubleQuoteJS($work['website_day_accessed']);
				
				$lastNameJS = "";
				if ($count == 1)
				{	
					$lastName = getLastName($exp[0]);
					$result = $lastName . ", " . getInitialFirstName($exp[0]) . ".";
					$lastNameJS = doubleQuoteJS($lastName);										
					
					$citationOptions = $lastNameJS . ', ' . $work['name_of_webpage'] .'(' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
					$citationOptions = "(" . $lastNameJS . ', ' . $work['name_of_webpage'] . ',' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
				}
				else
				{
					$tempCitation = "";
					for($i = 0; $i < $count; $i++)
					{
						$lastName = getLastName($exp[$i]);					
						$tempLastNameJS = doubleQuoteJS($lastName);
						if( $i == $count - 1)
						{
							if ($count < 7)
							{
								$result .= "&" . $lastName . ", " . getInitialFirstName($exp[$i]);
							}
							else
							{
								$result .= "..." . $lastName . ", " . getInitialFirstName($exp[$i]);
							}
							
							if ($count < 3)
							{							
								$tempCitation =  substr($tempCitation, 0, strlen($tempCitation) - 2);
								
								$citationOptions = $tempCitation . ' and ' . $tempLastNameJS . '(' . $year . ')';
								$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
								$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
								
								$citationOptions = "(" . $tempCitation . ' & ' . $tempLastNameJS . ',' . $year . ')';	
								$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
								$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
							}
						}
						else
						{
							$result .= $lastName . ", " . getInitialFirstName($exp[$i]) . "., ";
							if ($count < 3)
							{
								$tempCitation .= $tempLastNameJS . ", ";
							}
						}						
					}
				}
				
				if ($count >= 3)
				{				
					$lastName = getLastName($exp[0]);						
					$citationOptions = $lastName . ' et al (' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
					
					$citationOptions = '(' . $lastName . ' et al, ' . $year . ')';
					$citationList .= '"citation_' . $index++ . '":"' . $citationOptions . '",';
					$citationToInsert .= str_replace(",", "_S_S_", $citationOptions) . ",";
				}
				
				if ($count < 6)
				{	
					$result .= "(" . $year . "," . $month . " " . $day . ")<i>. de. Retrieved</i>. " . 
						$day_accessed . " " . $month_accessed . ", " . $year_accessed ."), from " . $work['name_of_webpage'] . ": ". $work['website_url'] . ".";
				}
				else
				{
					$result .= "(" . $year . "," . $month . " " . $day . ")<i>. de. Retrieved</i>. " . 
						$day_accessed . " " . $month_accessed . ", " . $year_accessed ."), from " . $work['name_of_webpage'] . ": ". $work['website_url'] . ".";
				}
						
			}
		echo $result; ?>    
                        <!--<span><a href="index.php?page=assignment_manager&_e=<?php echo $work['id'];?>&_t=<?php echo $work['types']?>">
        <img src="./images/edit.jpg" border="0" title="EDIT" alt="EDIT" /></a></span>&nbsp;&nbsp;
        <span><a href="javascript:void(0)" onclick="if(confirm('Are you sure you want to delete this?'))Del_Refernce(this,'<?php echo $work['id'];?>');">
        <img src="./images/delete.jpg" border="0" title="DELETE" alt="DELETE" /></a></span>-->
                        </div><br />
                        <?php } ?>
                    </td>
                </tr>
            </table>
        </td>
        <!-- // end -->
    </tr>
    <tr>
    	<td colspan="3" height="10px">&nbsp;</td>
    </tr>
</table>